package com.youlu.campus.service.data;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.youlu.campus.entity.*;
import com.youlu.campus.entity.VO.req.BuildDataExcelVO;
import com.youlu.campus.entity.VO.res.ExportBuildDataExcel;
import com.youlu.campus.entity.VO.res.ExportUserActivitySignUpRes;
import com.youlu.campus.service.visitor.UserInfoExtendService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class BuildDataExcelService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private UserInfoExtendService userInfoExtendService;

    public void initUserOrderAddress(List<BuildDataExcelVO> importExcelDataList) {
        if (CollectionUtils.isEmpty(importExcelDataList)) {
            return;
        }
        log.info("【导入excel数据订单补齐查找】 start BuildDataExcelService.initUserOrderAddress size - >{}",
                importExcelDataList.size());
        List<String> orderNoList =
                importExcelDataList.stream().map(BuildDataExcelVO::getMobile).collect(Collectors.toList());
        Query query = new Query();
        query.addCriteria(Criteria.where("orderNo").in(orderNoList));
        List<OrderInfo> orderInfoList = this.mongoTemplate.find(query, OrderInfo.class);
        if(CollectionUtils.isEmpty(orderInfoList)){
            return;
        }
        orderInfoList.stream().forEach(orderInfo -> {
            UserInfoExtend user = userInfoExtendService.findByUserId(orderInfo.getAccountInfoId());
            if(Objects.nonNull(user)){
                if(user.checkUserAdress()){
                    log.info("【导入excel数据订单补齐查找】BuildDataExcelService.initUserOrderAddress 更新用户->{}订单->{}地址- >{}",
                            user.getName(),orderInfo.getOrderNo());
                    orderInfo.setName(user.getReceiveName());
                    orderInfo.setMobile(user.getReceiveMobile());
                    orderInfo.setProvince(user.getProvince());
                    orderInfo.setCity(user.getCity());
                    orderInfo.setArea(user.getArea());
                    orderInfo.setAddress(user.getAddress());
                    orderInfo.setMark("初始化地址数据");
                    this.mongoTemplate.save(orderInfo);
                }
            }
        });
        log.info("【导入excel数据订单补齐查找】BuildDataExcelService.initUserOrderAddress end");
    }

    public void buildDataExcel(List<BuildDataExcelVO> importExcelDataList) {
        if (CollectionUtils.isEmpty(importExcelDataList)) {
            return;
        }
        log.info("【导入excel数据补齐查找】BuildDataExcelService.buildDataExcel size - >{}", importExcelDataList.size());
        ExcelWriter excelWriter = null;
        WriteSheet writeSheet = null;
        String fileName = "补全用户数据" + System.currentTimeMillis() + ExcelTypeEnum.XLSX.getValue();
        String file = "/data/app/file/" + fileName;
        Integer limit = 10000;
        Integer skip = 0;
        List<BuildDataExcelVO> limitRecord = null;
        excelWriter = EasyExcel.write(file, ExportBuildDataExcel.class).build();
        try {
            do {
                log.info("【导出excel数据补齐查找】BuildDataExcelService.buildDataExcel 开始批量处理list中第 {} 页 数据 总数据大小 - > {}", skip,
                        importExcelDataList.size());
                limitRecord = importExcelDataList.stream().skip(skip * limit).limit(limit).collect(Collectors.toList());
                List<String> mobileList =
                        limitRecord.stream().filter(u -> StringUtils.isNotBlank(u.getMobile())).map(u -> u.getMobile()).collect(Collectors.toList());
                log.info("【导出excel数据补齐查找】BuildDataExcelService.buildDataExcel mobileSize - >{}", mobileList.size());
                Query query = new Query();
                query.addCriteria(Criteria.where("mobile").in(mobileList));
                query.addCriteria(Criteria.where("universityId").exists(Boolean.TRUE));
                query.addCriteria(Criteria.where("name").exists(Boolean.TRUE));
                query.with(Sort.by(Sort.Direction.DESC, "id"));
                List<UserParticipateActivityInfo> userList = this.mongoTemplate.find(query, UserParticipateActivityInfo.class);
                if(CollectionUtils.isNotEmpty(userList)){
                    List<ExportBuildDataExcel> exportList = userList.stream().map(user -> {
                        ExportBuildDataExcel exportBuildDataExcel = new ExportBuildDataExcel();
                        exportBuildDataExcel.setMobile(user.getMobile());
                        exportBuildDataExcel.setName(user.getName());
                        if (StringUtils.isBlank(user.getUniversityName())) {
                            UniversityInfo universityInfo = this.mongoTemplate.findById(user.getUniversityId(),
                                    UniversityInfo.class);
                            if (Objects.nonNull(universityInfo)) {
                                exportBuildDataExcel.setUniversityName(universityInfo.getName());
                            }
                        } else {
                            exportBuildDataExcel.setUniversityName(user.getUniversityName());
                        }
                        return exportBuildDataExcel;
                    }).collect(Collectors.toList());
                    log.info("【导出excel数据补齐查找】BuildDataExcelService.buildDataExcel 写入文件", exportList.size());
                    writeSheet = EasyExcel.writerSheet("").build();
                    excelWriter.write(exportList, writeSheet);
                }

                skip++;
            } while (Objects.nonNull(limitRecord) && !limitRecord.isEmpty());

        }catch (Exception e){
            log.info("【导出excel数据补齐查找】BuildDataExcelService.buildDataExcel error", e);
        }finally {
            if (Objects.nonNull(excelWriter)) {
                excelWriter.finish();
            }
        }
        importExcelDataList.clear();
        log.info("【导出excel数据补齐查找】BuildDataExcelService.buildDataExcel 已结束");
    }
}
